﻿using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.Regions.Delete;

public class DeleteRegionsCommandHandler : IRequestHandler<DeleteRegionsCommandRequest>
{
    private readonly IRegionRepository _regionRepository;

    public DeleteRegionsCommandHandler(IRegionRepository regionRepository)
    {
        _regionRepository = regionRepository;
    }

    public async Task Handle(DeleteRegionsCommandRequest request, CancellationToken cancellationToken)
    {
        var region = await _regionRepository.FirstOrDefaultWithChildRegionsAsync(x => x.Id == request.RegionId, cancellationToken);
        if (region == null) throw new NotFoundException($"Регион с id '{request.RegionId}' не найден");
        if (region.ChildRegions.Any()) throw new BadRequestException($"Регион '{region.Id} является родительским для других регионов: '{string.Join("', '", region.ChildRegions.Select(x => x.Id))}'");

        await _regionRepository.DeleteAsync(region, cancellationToken);
    }
}